package funcSless

import (
	"fmt"

	"gitee.com/wchpub/fnsvr"
	"github.com/redis/go-redis/v9"
)

// 函数调用过程中的玩家数据缓存
type PlayerData struct {
	playerId string
	blocks   map[string]i_block
}

// 获取数据块
func GetBlock[KEY_TYPE ~string](m *PlayerData, blockName string) (*Block[KEY_TYPE], error) {
	_, ok := gFuncSlessEnv.BlockDefine[blockName]
	if !ok {
		return nil, fmt.Errorf("playerData.GetBlock block not found blockName:%s", blockName)
	}

	re, ok := m.blocks[blockName]

	if !ok {
		//创建一个数据块
		re = newBlock[KEY_TYPE](m.playerId, blockName)
		m.blocks[blockName] = re
	}

	return re.(*Block[KEY_TYPE]), nil
}

// 增量存档
func (m *PlayerData) save(pipe *redis.Pipeliner, changedBlocks map[string]int64) {

	//遍历 blocks
	for blockName, block := range m.blocks {
		change, err := block.save(pipe)
		if err != nil {
			fnsvr.Log().Error("playerData.save block.save", "blockName", blockName, "err", err)
			continue
		}

		if change {
			changedBlocks[makeBlockDirtyFieldName(m.playerId, blockName)] = 1
		}
	}

}

// 创建一个玩家数据缓存
func newPlayerData(playerId string) *PlayerData {
	return &PlayerData{
		blocks:   make(map[string]i_block),
		playerId: playerId,
	}
}
